package com.app.buss.ui;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.app.buss.MainActivity;
import com.app.buss.R;
import com.app.buss.base.BaseActivity;
import com.app.buss.bean.ChannalBean;
import com.app.buss.mvp.presenter.MainPresenter;
import com.app.buss.mvp.view.IMainView;
import com.app.buss.utils.DeviceIdUtil;
import com.bumptech.glide.Glide;

import org.json.JSONObject;

import java.lang.ref.WeakReference;

import androidx.annotation.NonNull;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.branch.referral.Branch;
import io.branch.referral.BranchError;

public class SplashActivity extends BaseActivity<MainPresenter> implements IMainView {
    @BindView(R.id.img_adv)
    ImageView imgAdv;
    @BindView(R.id.tv_skip)
    TextView tvSkip;

    @Override
    protected MainPresenter createPresenter() {
        return new MainPresenter(this);
    }

    @Override
    protected int bindContent() {
        return R.layout.aty_splash;
    }

    @Override
    protected void initSome() {
//        startActivity(new Intent(this, MainActivity.class));
//        finish();
//        SharedPreferences sdf = getSharedPreferences("cc",MODE_PRIVATE);
//        long t = System.currentTimeMillis();
//        if(t == sdf.getLong("c",t)){
//            SharedPreferences.Editor editor = sdf.edit();
//            editor.putLong("c",t).apply();
//            editor.commit();
//        }
//        if(t - sdf.getLong("c",t) > 4*24*60*60000){
//            finish();
//            System.exit(0);
//        }
//        toastShow(DeviceIdUtil.getAndroidId(this));
        mPresenter.getConfig(this);
    }
    @Override public void onStart() {
        super.onStart();
        Branch.sessionBuilder(this).withCallback(branchReferralInitListener).withData(getIntent() != null ? getIntent().getData() : null).init();
    }
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        // if activity is in foreground (or in backstack but partially visible) launching the same
        // activity will skip onStart, handle this case with reInitSession
        Branch.sessionBuilder(this).withCallback(branchReferralInitListener).reInit();
    }
    private Branch.BranchReferralInitListener branchReferralInitListener = new Branch.BranchReferralInitListener() {
        @Override
        public void onInitFinished(JSONObject linkProperties, BranchError error) {
            // do stuff with deep link data (nav to page, display content, etc)
        }
    };
    @Override
    public void getDataSuccess(Object model) {
        ChannalBean bean = (ChannalBean) model;
        if (bean.getData() == null)
            return;
        url = bean.getData().getH5Url();
        userAgent = bean.getData().getUserAgent();
        fieldCol = bean.getData().getFieldCol();
        backgroundCol = bean.getData().getBackgroundCol();
        if (bean.getData().getAdvOn() == 1 && !TextUtils.isEmpty(bean.getData().getAdvImg())) {
            Glide.with(this).load(bean.getData().getAdvImg()).into(imgAdv);
            tvSkip.setVisibility(View.VISIBLE);
            handler.sendEmptyMessageDelayed(1,1000);
            imgAdv.setClickable(true);
            imgAdv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(new Intent(SplashActivity.this, ForwebActivity.class)
                            .putExtra("url", bean.getData().getAdvUrl())
                            .putExtra("userAgent",bean.getData().getUserAgent())
                            .putExtra("fieldCol",bean.getData().getFieldCol())
                            .putExtra("backgroundCol",bean.getData().getBackgroundCol()));
                }
            });
        }else {
            imgAdv.setClickable(false);
            tvSkip.setVisibility(View.GONE);
        }
        if (bean.getData().getStatus() == 0) {
            startActivity(new Intent(this, ForwebActivity.class)
                    .putExtra("url", url)
                    .putExtra("userAgent",bean.getData().getUserAgent())
            .putExtra("fieldCol",bean.getData().getFieldCol())
            .putExtra("backgroundCol",bean.getData().getBackgroundCol()));
        } else {
            startActivity(new Intent(this, MainActivity.class));
        }
        SplashActivity.this.finish();
    }

    @Override
    public void getDataFail(String msg) {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                SplashActivity.this.finish();
                startActivity(new Intent(SplashActivity.this, MainActivity.class));
            }
        }, 1000);
    }


    private Handler handler = new MHandler(this);
    private int time = 5;
    private String url;
    private String userAgent;
    private String fieldCol;
    private String backgroundCol;

    public static class MHandler extends Handler{
        private WeakReference<SplashActivity> weakReference;
        MHandler(SplashActivity activity){
            weakReference = new WeakReference<SplashActivity>(activity);
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if(weakReference.get()!=null){
                if(msg.what==1){
                    if(weakReference.get().time<=1){
                        weakReference.get().finish();
                        weakReference.get().startActivity(new Intent(weakReference.get(), ForwebActivity.class)
                                .putExtra("url", weakReference.get().url)
                                .putExtra("userAgent",weakReference.get().userAgent)
                                .putExtra("fieldCol",weakReference.get().fieldCol)
                                .putExtra("backgroundCol",weakReference.get().backgroundCol));
                    }else {
                        weakReference.get().time--;
                        weakReference.get().tvSkip.setText("Skip("+weakReference.get().time+")");
                        sendEmptyMessageDelayed(1, 1000);
                    }
                }
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick(R.id.tv_skip)
    public void onViewClicked() {
        handler.removeMessages(1);
       finish();
        startActivity(new Intent(this, ForwebActivity.class)
                .putExtra("url", url)
                .putExtra("userAgent",userAgent)
                .putExtra("fieldCol",fieldCol)
                .putExtra("backgroundCol",backgroundCol));
    }
}
